package com.netease.yunxin.kit.conversationkit.ui.page

import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.drake.brv.utils.addModels
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.mutable
import com.drake.brv.utils.setup
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luoxiang.lib_common.bean.NumberBean
import com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA
import com.luoxiang.lib_common.common.Constants.MmkvConst.KEY
import com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN
import com.luoxiang.lib_common.utils.AESUtil
import com.luoxiang.lib_common.utils.MmkvUtil.decodeString
import com.luoxiang.lib_common.utils.NetUtils
import com.netease.yunxin.kit.common.ui.fragments.BaseFragment
import com.netease.yunxin.kit.conversationkit.ui.R
import com.netease.yunxin.kit.conversationkit.ui.databinding.FragmentConversationCallBinding
import com.netease.yunxin.kit.conversationkit.ui.model.VideoCallListBean
import com.netease.yunxin.kit.conversationkit.ui.model.VideoCallListBeanList
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
 * Author: Sakura

 * Date: 2023/4/21

 * Description:
 */
class ConversationCallFragment : BaseFragment() {

    private lateinit var binding: FragmentConversationCallBinding

    private var mIsLoaded = false

    private var mPageNum = 1

    private val mPageSize = 20

    private var mIsLoad: Boolean = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentConversationCallBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.refresh.setEnableOverScrollDrag(true)
        binding.refresh.setOnLoadMoreListener {
            mIsLoad = true
            mPageNum += 1
            initData()
        }
        binding.refresh.setOnRefreshListener {
            mPageNum = 1
            initData()
        }
        initRecyclerView()
    }

    override fun onResume() {
        super.onResume()
        if (!mIsLoaded && !isHidden) {
            initData()
        }
    }

    private fun initRecyclerView() {
        binding.recycler.linear().setup {
            addType<VideoCallListBeanList>(R.layout.item_conversation_cancel)
            onBind {
                (getModel(modelPosition) as VideoCallListBeanList).let {
                    Glide.with(requireActivity())
                        .load("https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/" + it.icon)
                        .transform(CenterCrop(), CircleCrop())
                        .into(findView(R.id.imageCover))
                    findView<TextView>(R.id.textUserName).text = "·${it.name}"
                    findView<TextView>(R.id.textTime).text = it.interval
                    if (it.online == 1) {
                        findView<ImageView>(R.id.imageOnline).visibility = View.VISIBLE
                    } else {
                        findView<ImageView>(R.id.imageOnline).visibility = View.GONE
                    }

                    when (it.status) {
                        1 -> {
                            findView<ImageView>(R.id.imageState).setImageResource(R.drawable.icon_call_20)
                            findView<TextView>(R.id.testState).text = it.duration
                        }

                        2 -> {
                            findView<ImageView>(R.id.imageState).setImageResource(R.drawable.icon_removed_20)
                            findView<TextView>(R.id.testState).text = "已取消"
                        }

                        3 -> {
                            findView<ImageView>(R.id.imageState).setImageResource(R.drawable.icon_missed_call_20)
                            findView<TextView>(R.id.testState).text = "已拒绝"
                        }

                        4 -> {
                            findView<ImageView>(R.id.imageState).setImageResource(R.drawable.icon_removed_20)
                            findView<TextView>(R.id.testState).text = "未接听"
                        }

                        5 -> {
                            findView<ImageView>(R.id.imageState).setImageResource(R.drawable.icon_removed_20)
                            findView<TextView>(R.id.testState).text = "对方占线中"
                        }
                    }

                    when (it.type) {
                        -1 -> {
                            findView<ImageView>(R.id.imageBadReviews).setImageResource(R.drawable.icon_rating_dislike_unselected_24)
                            findView<ImageView>(R.id.imageGoodReviews).setImageResource(R.drawable.icon_rating_like_unchecked_24)
                        }

                        1 -> {
                            findView<ImageView>(R.id.imageBadReviews).setImageResource(R.drawable.icon_rating_dislike_selected_24)
                            findView<ImageView>(R.id.imageGoodReviews).setImageResource(R.drawable.icon_rating_like_unchecked_24)
                        }

                        0 -> {
                            findView<ImageView>(R.id.imageBadReviews).setImageResource(R.drawable.icon_rating_dislike_unselected_24)
                            findView<ImageView>(R.id.imageGoodReviews).setImageResource(R.drawable.icon_rating_like_check_24)
                        }
                    }
                }
            }
            onClick(R.id.imageCover) {
                (getModel(modelPosition) as VideoCallListBeanList).let {
                    LiveEventBus.get<String>("startDetailsActivity").post(it.userId)
                }
            }
            onLongClick(R.id.roots) {
                (getModel(modelPosition) as VideoCallListBeanList).let {
                    AlertDialog.Builder(requireContext()).apply {
                        setTitle("是否删除通话记录")
                        setCancelable(true)
                        setPositiveButton(
                            "删除"
                        ) { p0, p1 ->
                            remove(it.id, modelPosition)
                        }
                        setNegativeButton("取消") { _, _ ->

                        }
                    }.show()
                }
            }
        }
    }

    private fun initData() {
        mIsLoaded = true
        NetUtils.getInstance().apiService.getVideoCallList(
            EXTRA,
            decodeString(TOKEN),
            mPageNum,
            mPageSize
        ).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean> {
                override fun onSubscribe(d: Disposable?) {}

                override fun onError(e: Throwable?) {
                    Toast.makeText(requireContext(), e?.message, Toast.LENGTH_SHORT).show()
                }

                override fun onComplete() {}

                override fun onNext(value: NumberBean?) {
                    binding.refresh.finishRefresh()
                    binding.refresh.finishLoadMore()
                    value?.data?.let {
                        val json = AESUtil.aesDecryptString(it, KEY)
                        val bean = Gson().fromJson(json, VideoCallListBean::class.java)
                        if (bean?.data?.hosts?.isNotEmpty() == true) {
                            if (mIsLoad) {
                                binding.recycler.addModels(bean.data.hosts)
                                return@let
                            }
                            binding.recycler.models = bean.data.hosts
                        } else {
                            binding.refresh.finishLoadMoreWithNoMoreData()
                        }
                    }
                }
            })
    }

    private fun remove(id: Int?, position: Int) {
        id ?: return
        NetUtils.getInstance().apiService.removeVideoCallLog(
            EXTRA,
            decodeString(TOKEN),
            id
        ).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean> {
                override fun onSubscribe(d: Disposable?) {}

                override fun onError(e: Throwable?) {
                    Toast.makeText(requireContext(), e?.message, Toast.LENGTH_SHORT).show()
                }

                override fun onComplete() {}

                override fun onNext(value: NumberBean?) {
                    binding.refresh.finishRefresh()
                    binding.refresh.finishLoadMore()
                    value?.data?.let {
                        val json = AESUtil.aesDecryptString(it, KEY)
                        val bean = Gson().fromJson(json, VideoCallListBean::class.java)
                        if (bean.code == 0) {
                            binding.recycler.mutable.removeAt(position)
                            binding.recycler.bindingAdapter.notifyItemRemoved(position) // 然后刷新列表
                        } else {
                            Toast.makeText(requireContext(), bean.msg, Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
    }
}